package com.gcb.framework.security.handle;

import cn.hutool.core.util.ObjUtil;
import com.gcb.common.constant.Constants;
import com.gcb.common.core.domain.entity.GcbUser;
import com.gcb.common.core.redis.RedisCache;
import com.gcb.common.utils.StringUtils;
import com.gcb.framework.model.AppLoginUser;
import com.gcb.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

@Component
public class AuthTouristTokenUtils {

    // 令牌自定义标识
    @Value("${token.touristToken}")
    private String touristToken;

    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    @Resource
    private TokenService tokenService;

    @Resource
    private RedisCache redisCache;

    public void authTouristToken(HttpServletRequest request) {
        String token = Optional.ofNullable(request.getHeader(header)).orElse(request.getParameter(header));
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        //判断是否为游客token
        if (touristToken.equals(token)) {
            // 获取请求携带的令牌
            if (StringUtils.isNotEmpty(token)) {
                Claims claims = tokenService.parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(Constants.APP_LOGIN_USER_KEY);
                String userKey = tokenService.getTokenKey(uuid);
                AppLoginUser appUser = redisCache.getCacheObject(userKey);
                if (ObjUtil.isNull(appUser)) {
                    appUser = new AppLoginUser();
                    appUser.setUserId(1772437666129485824L);
                    appUser.setToken(uuid);
                    appUser.setLoginTime(System.currentTimeMillis());

                    GcbUser gcbUser = new GcbUser();
                    gcbUser.setId(1772437666129485824L);
                    gcbUser.setName("游客");
                    gcbUser.setNickName("游客");
                    gcbUser.setSex(2);
                    gcbUser.setAge(35);
                    gcbUser.setStatus(1);
                    gcbUser.setDelFlag(0);
                    gcbUser.setMobile("13000000000");
                    appUser.setAppUser(gcbUser);
                    // 根据uuid将loginUser缓存
                    redisCache.setCacheObject(userKey, appUser);
                }
            }
        }
    }
}
